package com.winning.devops.cloud.id.time.impl;

import javax.sql.DataSource;
import java.sql.*;

/**
 * 通过SQL获取数据库时间
 * @author chensj@winning.com.cn
 */
public class SqlTimeService extends AbstractTimeService {
    /**
     * mysql 数据库查询时间sql
     */
    //private String timestampSql = "select now() from dual";
    /**
     * 数据库查询时间sql
     */
    private String timestampSql;
    /**
     * 数据库连接
     */
    private DataSource dataSource;

    public void setTimestampSql(String timestampSql) {
        this.timestampSql = timestampSql;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    /**
     * 获取数据库时间
     * @return
     */
    protected long remoteTimestamp() {
        Connection conn = null;
        try {
            conn = this.dataSource.getConnection();
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(this.timestampSql);
            long localDateTime = System.currentTimeMillis();
            if (rs.next()) {
                Timestamp localTimestamp = rs.getTimestamp(1);
                localDateTime = localTimestamp.getTime();
            }
            rs.close();
            stmt.close();
            return localDateTime;
        } catch (SQLException e) {
            throw new IllegalStateException("cannot get timestamp from database.");
        } finally {
            try {
                conn.close();
            } catch (SQLException e) {
            }
        }
    }
}
